﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Browser;

namespace Songhay.Silverlight.Mvvm
{
    using Songhay.Extensions;

    /// <summary>
    /// Static members
    /// for <see cref="System.Windows.Browser.HtmlPage"/>.
    /// </summary>
    public static class HtmlPageUtility
    {
        /// <summary>
        /// Gets the conventional Client settings.
        /// </summary>
        /// <param name="settingsElementId">The settings element id.</param>
        public static Dictionary<string, string> GetClientSettings(string settingsElementId)
        {
            var settings = HtmlPage.Document.GetElementById(settingsElementId);
            if(settings == null) throw new ArgumentException(
                string.Format("Client configuration " + 
                    "settings at “{0}” not found.", settingsElementId));

            var dictionary = new Dictionary<string, string>();

            var fieldset = settings.Children
                .OfType<HtmlElement>()
                .FirstOrDefault(f => f.TagName == "fieldset");
            if(fieldset == null) throw new ArgumentException(
                string.Format("Client configuration settings " +
                    "in conventional fieldset at “{0}” not found.",
                    settingsElementId));
            fieldset.Children.OfType<HtmlElement>()
                .Where(e => e.TagName == "input")
                .ForEachInEnumerable(
                    input =>
                    {
                        var x = input.GetAttribute("value");
                        if(!string.IsNullOrEmpty(x))
                            dictionary.Add(input.Id, x);
                    });
            return dictionary;
        }
    }
}
